unit ec_monospacedtextbase;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons,
  StdCtrls, ec_base;

type

  { TECMonospacedTextBaseFrame }

  TECMonospacedTextBaseFrame = class(TECBaseFrame)
    ContentsMemo: TMemo;
    procedure FormShow(Sender: TObject);
  private
    procedure InitialSetUp;
  public
    function GetCommandCode: Integer; virtual; abstract;
    function GetContinuationCommandCode: Integer; virtual; abstract;
    procedure InitNew; override;
    procedure InitExisting; override;
    procedure MakeResultingCommand; override;
  end;

var
  ECMonospacedTextBaseFrame: TECMonospacedTextBaseFrame;

implementation

uses
  gamefont, fpjson;

{$R *.lfm}

{ TECMonospacedTextBaseFrame }

procedure TECMonospacedTextBaseFrame.FormShow(Sender: TObject);
begin
  ContentsMemo.SetFocus
end;

procedure TECMonospacedTextBaseFrame.InitialSetUp;
begin
  with ContentsMemo.Font do begin
    BeginUpdate;
    Name := GetMonospacedFontName;
    Size := GetMonospacedFontSize;
    EndUpdate
  end
end;

procedure TECMonospacedTextBaseFrame.InitNew;
begin
  InitialSetUp
end;

procedure TECMonospacedTextBaseFrame.InitExisting;
var
  List: TStringList;
  Cmd: TJSONObject = nil;
  Params: TJSONArray = nil;
  I: Integer;
  InitialCode, ContinuationCode: Integer;
begin
  InitialSetUp;
  List := TStringList.Create;
  InitialCode := GetCommandCode;
  ContinuationCode := GetContinuationCommandCode;

  I := ListIndex;
  while I < EcList.Count do begin
    Cmd := EcList.Objects[I];

    if Cmd = nil then
       Break;
    if (I = ListIndex) and (Cmd.Integers['code'] <> InitialCode) then
       Break;
    if (I > ListIndex) and (Cmd.Integers['code'] <> ContinuationCode) then
       Break;

    if Cmd.Find('parameters', Params) and (Params.Count >= 1) and
         (Params[0].JSONType = jtString) then
      List.Add(Params.Strings[0])
    else
      List.Add('');

    Inc(I);
  end;

  ContentsMemo.Text := List.Text;

  List.Free
end;

procedure TECMonospacedTextBaseFrame.MakeResultingCommand;
var
 List: TStringList;
 Line: String;
 IsFirst: Boolean = True;
 Code: Integer;
begin
  ResultingCommand := TJSONArray.Create();

  List := TStringList.Create;
  List.Text := ContentsMemo.Text;
  for Line in List do begin
    if IsFirst then begin
      Code := GetCommandCode;
      IsFirst := False;
    end else
      Code := GetContinuationCommandCode;

    ResultingCommand.Add(TJSONObject.Create([
      'code', Code,
      'indent', Indent,
      'parameters', TJSONArray.Create([Line])
    ]))
  end;
  List.Free
end;

end.

